package com.tianyang.yukuaifuzs.module.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.tianyang.yukuaifuzs.R;
import com.tianyang.yukuaifuzs.base.YkfApplication;
import com.tianyang.yukuaifuzs.business.main.bean.AppVersionOutput;
import com.tianyang.yukuaifuzs.common.interfaces.CommonConfig;
import com.tianyang.yukuaifuzs.common.service.DownloadIntentService;
import com.tianyang.yukuaifuzs.common.service.SPDownloadUtil;
import com.tianyang.yukuaifuzs.common.view.TasksCompletedView;
import com.tianyang.yukuaifuzs.jump.eventbus.RefreshDownloadEvent;
import com.tianyang.yukuaifuzs.utils.AppContextUtil;
import com.tianyang.yukuaifuzs.utils.IntentTool;
import com.tianyang.yukuaifuzs.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Description：版本更新弹框
 * Created by 薛勇军 on 2019/1/11.
 */

public class CheckVersionDialog extends Dialog {

    @BindView(R.id.versionTitleTv)
    TextView versionTitleTv;
    @BindView(R.id.versionRemarkTv)
    TextView versionRemarkTv;
    @BindView(R.id.hintTv)
    TextView hintTv;
    @BindView(R.id.closeTv)
    TextView closeTv;

    @BindView(R.id.showViewLl)
    LinearLayout showViewLl;
    @BindView(R.id.loadingLl)
    LinearLayout loadingLl;
    @BindView(R.id.successLl)
    LinearLayout successLl;
    @BindView(R.id.completedView)
    TasksCompletedView completedView;
    @BindView(R.id.loadingBgIv)
    ImageView loadingBgIv;

    private Context mContext;

    private String updateDownloadPath;

    private String mDownloadFileName;

    private boolean isUpdateApp = false;//是否app内更新

    public CheckVersionDialog(Context context, AppVersionOutput retDatBean) {
        super(context, R.style.dialog_normal);
        setContentView(R.layout.view_check_version);
        ButterKnife.bind(this);
        setCancelable(false);
        EventBus.getDefault().register(this);
        this.mContext = context;

        completedView.setProgress(0);
        if (retDatBean != null) {
            if (TextUtils.equals("1", retDatBean.getIfUpdate())) {
                hintTv.setVisibility(View.VISIBLE);
                closeTv.setVisibility(View.GONE);
            } else {
                hintTv.setVisibility(View.GONE);
                closeTv.setVisibility(View.VISIBLE);
            }
            if (!TextUtils.isEmpty(retDatBean.getRemark())) {
                versionRemarkTv.setText(retDatBean.getRemark());
            }
            if (!TextUtils.isEmpty(retDatBean.getVersionNo())) {
                versionTitleTv.setText(retDatBean.getVersionNo()+"版本更新");
            }
//            if (!TextUtils.isEmpty(retDatBean.getDownUrl())) {
                updateDownloadPath = retDatBean.getDownUrl();
//                mDownloadFileName = updateDownloadPath.substring(updateDownloadPath.lastIndexOf("/") + 1);
//                isUpdateApp = true;
//            } else {
//                updateDownloadPath = retDatBean.getUrl();
//                isUpdateApp = false;
//            }
        }
    }

    @OnClick({R.id.confirmRtv, R.id.installRtv, R.id.closeTv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.confirmRtv:
                if (!TextUtils.isEmpty(updateDownloadPath) && updateDownloadPath.startsWith("http")) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(updateDownloadPath);
                    intent.setData(content_url);
                    IntentTool.startActivity(getContext(), intent);
                }
//                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
//                    if (!PermissionsMgr.getInstance().hasPermission(mContext, PermissionsConstant.WRITE_STORAGE)) {
//                        ((BaseFragmentActivity) mContext).requestPermissions(PermissionsConstant.WRITE_STORAGE);
//                        return;
//                    }
//                }
//                if (!TextUtils.isEmpty(updateDownloadPath)) {
//                    if (isUpdateApp) {
//                        refreshView(1);
//                        startDownloadService();
//                    } else {
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        Uri content_url = Uri.parse(updateDownloadPath);
//                        intent.setData(content_url);
//                        IntentTool.startActivity(getContext(), intent);
//                    }
//                }
                break;
            case R.id.installRtv:
                File file = new File(CommonConfig.APP_ROOT_PATH + CommonConfig.DOWNLOAD_DIR + mDownloadFileName);
                if (file.exists()) {
                    installApp(file);
                } else {
                    completedView.setProgress(0);
                    loadingBgIv.setVisibility(View.GONE);
                    refreshView(1);
                    SPDownloadUtil.getInstance().clear();
                    startDownloadService();
                }
                break;
            case R.id.closeTv:
                dismiss();
                break;
        }
    }

    /**
     * 开始启动服务下载
     */
    private void startDownloadService() {
        if (AppContextUtil.isServiceRunning(getContext(), DownloadIntentService.class.getName())) {
            ToastUtil.show("正在下载，请稍后...");
            return;
        }
        Intent intent = new Intent(getContext(), DownloadIntentService.class);
        Bundle bundle = new Bundle();
        bundle.putString("download_url", updateDownloadPath);
        bundle.putString("download_file", mDownloadFileName);
        bundle.putString("download_id", "10");
        intent.putExtras(bundle);
        getContext().startService(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshDownloadEvent(RefreshDownloadEvent event) {
        if (event != null) {
            if (event.getProgress() == 100) {
                completedView.setProgress(100);
                refreshView(2);
            } else if (event.getProgress() == -1) {
                ToastUtil.show("下载错误，请重新点击下载或退出应用程序重试！");
                refreshView(0);
            } else if (event.getProgress() == 0) {
                loadingBgIv.setVisibility(View.GONE);
            } else {
                completedView.setProgress(event.getProgress());
                loadingBgIv.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void installApp(File file) {
        //判断是否是AndroidN以及更高的版本
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(YkfApplication.getInstance(),
                    YkfApplication.getInstance().getPackageName() + ".fileProvider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        getContext().startActivity(intent);
    }

    /**
     * 刷新视图
     */
    private void refreshView(int showType) {
        showViewLl.setVisibility(View.GONE);
        successLl.setVisibility(View.GONE);
        loadingLl.setVisibility(View.GONE);
        switch (showType) {
            case 0:
                showViewLl.setVisibility(View.VISIBLE);
                break;
            case 1:
                loadingLl.setVisibility(View.VISIBLE);
                break;
            case 2:
                successLl.setVisibility(View.VISIBLE);
                break;
        }
    }
}
